<template>
  <view class="edit-page role-edit-page">
    <!-- 表单内容 -->
    <view class="form-content">
      <uni-forms
          ref="formRef"
          :modelValue="form"
          :rules="rules"
          labelWidth="100px">

        <uni-forms-item label="角色名称" name="roleName" required>
          <uni-easyinput
              v-model="form.roleName"
              placeholder="请输入角色名称"
              :clearable="true"
              :disabled="!canEdit">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="角色权限" name="roleKey" required>
          <uni-easyinput
              v-model="form.roleKey"
              placeholder="请输入角色权限字符串"
              :clearable="true"
              :disabled="!canEdit">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="显示排序" name="roleSort" required>
          <uni-number-box
              v-model="form.roleSort"
              :min="0"
              :max="999"
              :disabled="!canEdit">
          </uni-number-box>
        </uni-forms-item>

        <uni-forms-item label="角色状态" name="status">
          <uni-data-checkbox
              v-model="form.status"
              :localdata="statusOptions"
              mode="list"
              :disabled="!canEdit">
          </uni-data-checkbox>
        </uni-forms-item>

        <uni-forms-item label="备注" name="remark">
          <uni-easyinput
              v-model="form.remark"
              placeholder="请输入备注"
              type="textarea"
              :clearable="true"
              :disabled="!canEdit">
          </uni-easyinput>
        </uni-forms-item>

      </uni-forms>
    </view>

    <!-- 底部操作按钮 -->
    <view class="footer-actions">
      <view class="action-buttons">
        <view
            v-if="!isView"
            class="cancel-btn"
            @click="handleBack">
          取消
        </view>
        <view
            v-if="!isView"
            class="submit-btn"
            @click="handleSubmit">
          {{ pageType === 'add' ? '确认新增' : '保存修改' }}
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import {computed, getCurrentInstance, reactive, ref} from 'vue'
import {onLoad} from '@dcloudio/uni-app'
import {addRole, getRole, updateRole} from '@/api/system/role'

const {proxy} = getCurrentInstance()

// 页面参数
const pageType = ref('add')
const roleId = ref(null)
const submitting = ref(false)

// 计算属性
const isView = computed(() => pageType.value === 'view')
const canEdit = computed(() => pageType.value === 'add' || pageType.value === 'edit')

// 表单数据
const form = reactive({
  roleId: undefined,
  roleName: '',
  roleKey: '',
  roleSort: 0,
  status: '0',
  remark: ''
})

// 表单验证规则
const rules = {
  roleName: {
    rules: [
      {required: true, errorMessage: '角色名称不能为空'},
      {minLength: 2, maxLength: 30, errorMessage: '角色名称长度在2到30个字符'}
    ]
  },
  roleKey: {
    rules: [
      {required: true, errorMessage: '角色权限不能为空'},
      {minLength: 2, maxLength: 100, errorMessage: '角色权限长度在2到100个字符'}
    ]
  },
  roleSort: {
    rules: [
      {required: true, errorMessage: '显示排序不能为空'}
    ]
  }
}

// 选项数据
const statusOptions = ref([
  {value: '0', text: '正常'},
  {value: '1', text: '停用'}
])

// 组件引用
const formRef = ref()

// ==================== 修复：使用 onLoad 生命周期钩子 ====================
onLoad((options) => {
  pageType.value = options.mode || options.type || 'add'
  roleId.value = options.roleId || options.id || null

  // 设置页面标题
  const titleMap = {
    add: '新增角色',
    edit: '编辑角色',
    view: '查看角色'
  }
  uni.setNavigationBarTitle({
    title: titleMap[pageType.value] || '角色管理'
  })

  // 如果是编辑或查看模式，加载角色数据
  if ((pageType.value === 'edit' || pageType.value === 'view') && roleId.value) {
    getRoleInfo()
  }
})

// 获取角色信息
async function getRoleInfo() {
  try {
    const response = await getRole(roleId.value)
    if (response.code === 200) {
      Object.assign(form, response.data)
    } else {
      proxy.$modal.showToast(response.msg || '获取角色信息失败')
    }
  } catch (error) {
    console.error('获取角色信息失败:', error)
    proxy.$modal.showToast('获取角色信息失败')
  }
}

// 提交表单
async function handleSubmit() {
  if (submitting.value) return

  try {
    // 表单验证
    const valid = await formRef.value.validate()
    if (!valid) {
      return
    }

    submitting.value = true

    let response
    if (pageType.value === 'add') {
      response = await addRole(form)
      if (response.code === 200) {
        proxy.$modal.showToast('新增成功')
      }
    } else {
      response = await updateRole(form)
      if (response.code === 200) {
        proxy.$modal.showToast('修改成功')
      }
    }

    if (response.code === 200) {
      setTimeout(() => {
        handleBack()
      }, 1500)
    } else {
      proxy.$modal.showToast(response.msg || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    proxy.$modal.showToast('操作失败')
  } finally {
    submitting.value = false
  }
}

// 返回
function handleBack() {
  uni.navigateBack()
}
</script>

<style lang="scss" scoped>
@import '@/styles/edit-page.scss';
</style>
